/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.image;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ThumbnailUtils
{
    private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( ThumbnailUtils.class.getName() );
	static String EMPTY = "";
	static MediaTracker tracker;
	static Class cls;

	public ThumbnailUtils()
	{
	}

	/*static Thumbnail getThumbImage(File file, Dimension dimension)
	{
			return getThumbImage(file, dimension);
	} */
	
	public static void writeJPG(BufferedImage bufferedimage, OutputStream os, float quality) throws IOException
	{
	  JPEGImageEncoder jpegimageencoder = JPEGCodec.createJPEGEncoder(os);
	  JPEGEncodeParam jpegencodeparam = jpegimageencoder.getDefaultJPEGEncodeParam(bufferedimage);
	  jpegencodeparam.setQuality(quality, false);
	  jpegimageencoder.setJPEGEncodeParam(jpegencodeparam);
	  jpegimageencoder.encode(bufferedimage);
	  os.close();
	  jpegimageencoder = null;
	  System.gc();
	}
	
	public static void writeJPG(BufferedImage bufferedimage, File file, float quality) throws IOException
	{
		 writeJPG(bufferedimage, new FileOutputStream(file),quality);
	}

	public static BufferedImage getScaledimage(Image image, Dimension dimension)
	{
		int oldwidth = image.getWidth(null);
		int oldheight= image.getHeight(null);
		float aspectratio = ((float)oldwidth) / ((float)oldheight);
		int l;
		int i1;
		if(oldwidth > dimension.width)
		{
				l = dimension.width;
				i1 = (int)((float)l / aspectratio);
				if(i1 > dimension.height)
				{
						i1 = dimension.height;
						l = (int)(aspectratio * (float)i1);
				}
		} else if(oldheight > dimension.height)
		{
				i1 = dimension.height;
				l = (int)(aspectratio* (float)i1);
				if(l > dimension.width)
				{
						l = dimension.width;
						i1 = (int)((float)l / aspectratio);
				}
		} else
		{
				l = oldwidth;
				i1 = oldheight;
		}
		Image newimage = loadImage(image.getScaledInstance(l, i1, l<=640||i1<=480?Image.SCALE_FAST:Image.SCALE_DEFAULT));//
		image.flush();
		image = newimage;
		BufferedImage bufferedimage = new BufferedImage(l, i1, 1);
		java.awt.Graphics2D graphics2d = bufferedimage.createGraphics();
		graphics2d.drawImage(image, 0, 0, l, i1, null);
		image.flush();
		image = null;
		System.gc();
		return bufferedimage;
	}

	public static Thumbnail getThumbImage(File file, Dimension dimension) throws IOException
	{
//        String s = file.getName();
//        int i = s.length() - 4;
		Image obj = getImage(file); //Donde metemos la imagen original
		if (obj == null)
				throw new IllegalArgumentException("Can't get scaled image of a null Image object ("+file.getAbsolutePath()+")");
	
		Thumbnail thumbnail = new Thumbnail();
		thumbnail.origw = obj.getWidth(null);;
		thumbnail.origh = obj.getHeight(null);;
		thumbnail.nw = (int)dimension.getWidth();
		thumbnail.nh = (int)dimension.getHeight();
		thumbnail.bi = getScaledimage(obj,dimension);

		return thumbnail;
	}

	/**
	 * @deprecated Please use JPEGtoImage
	 * @param inputstream
	 * @return
	 * @throws IOException
	 */
	public static Image getImage(InputStream inputstream) throws IOException
	{
		return JPEGtoImage(inputstream);
	}

	public static Image JPEGtoImage(InputStream inputstream) throws IOException
	{
//		try
		{
			JPEGImageDecoder jpegimagedecoder = JPEGCodec.createJPEGDecoder(inputstream);
			Image image = jpegimagedecoder.decodeAsBufferedImage();
			inputstream.close();
			return image;
		} /*catch (com.sun.image.codec.jpeg.ImageFormatException e)
		{
			byte[]tmp = new byte[1024];
			ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
			int read;
			while ((read=inputstream.read(tmp))>0)
				bytearray.write(tmp,0,read);
		  return Toolkit.getDefaultToolkit().createImage(bytearray.toByteArray());
		}*/
	}
	public static Image getImage(File file) throws IOException
	{
		String s = file.getName();
		int i = s.length() - 4;
		Image obj = null;
		if(s.regionMatches(true, i, ".jpg", 0, 4))
		{
			FileInputStream fileinputstream = new FileInputStream(file);
			JPEGImageDecoder jpegimagedecoder = JPEGCodec.createJPEGDecoder(fileinputstream);
			obj = jpegimagedecoder.decodeAsBufferedImage();
			fileinputstream.close();
		}
		else if(s.regionMatches(true, i, ".gif", 0, 4))
				obj = loadImage(Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath()));//
		else if(s.regionMatches(true, i, ".bmp", 0, 4))
				obj = BMPUtils.load(file);
		else
		try
		{
			obj = Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());
			if(tracker == null)
					tracker = new MediaTracker(new Container());
			tracker.addImage(obj, 0);
			tracker.checkID(0);
			tracker.waitForAll();
		}
		catch(InterruptedException e)
		{
			log.error(e.getMessage(),e);
		}
			return obj;
    }
	
    static Image loadImage(Image image)
    {
			try
			{
					if(tracker == null)
							tracker = new MediaTracker(new Container());
					tracker.addImage(image, 0);
					tracker.waitForAll();
			}
			catch(Exception exception)
			{
				log.error(exception.getMessage(),exception);
				return null;
			}
			if(image.getWidth(null) <= 0)
					return null;
			else
					return image;
    }

	static boolean checkVersion()
	{
		String s = System.getProperty("java.version");
		if(s.compareTo("1.2") < 0)
		{
				return false;
		} else
		{
				return true;
		}
	}
	static void copyFile(File file, File file1) throws IOException
	{
		byte abyte0[] = new byte[512];
		FileInputStream fileinputstream = new FileInputStream(file);
		FileOutputStream fileoutputstream = new FileOutputStream(file1);
		int i;
		while((i = fileinputstream.read(abyte0)) > 0)
			fileoutputstream.write(abyte0, 0, i);
		fileinputstream.close();
		fileoutputstream.close();
	}
}
